import 'package:flutter/material.dart';

// 示例1: 基础状态管理 - 计数器
class CounterWidget extends StatefulWidget {
  const CounterWidget({Key? key, this.initValue = 0}) : super(key: key);

  final int initValue;

  @override
  State<CounterWidget> createState() => _CounterWidgetState();
}

class _CounterWidgetState extends State<CounterWidget> {
  int _counter = 0;

  @override
  void initState() {
    super.initState();
    // 初始化状态
    _counter = widget.initValue;
    print("initState");
  }

  @override
  Widget build(BuildContext context) {
    print("build");
    return Scaffold(
      appBar: AppBar(title: const Text('基础状态管理')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text('点击按钮增加计数:'),
            Text('$_counter', style: Theme.of(context).textTheme.titleLarge),
            ElevatedButton(
              onPressed: _increment,
              child: const Text('Increment'),
            ),
          ],
        ),
      ),
    );
  }

  void _increment() {
    setState(() {
      _counter++;
    });
  }
}

// 示例2: 父widget向子widget传值
class ParentWidget extends StatefulWidget {
  const ParentWidget({Key? key}) : super(key: key);

  @override
  State<ParentWidget> createState() => _ParentWidgetState();
}

class _ParentWidgetState extends State<ParentWidget> {
  String _message = '初始消息';

  void _updateMessage() {
    setState(() {
      _message = '更新后的消息 (${DateTime.now().second})';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('父向子传值')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ChildWidget(message: _message),
            ElevatedButton(
              onPressed: _updateMessage,
              child: const Text('更新消息'),
            ),
          ],
        ),
      ),
    );
  }
}

class ChildWidget extends StatelessWidget {
  final String message;

  const ChildWidget({Key? key, required this.message}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Text(
      '接收到的消息: $message',
      style: Theme.of(context).textTheme.titleLarge,
    );
  }
}

// 示例3: 子widget向父widget传值
class ParentToChildExample extends StatefulWidget {
  const ParentToChildExample({Key? key}) : super(key: key);

  @override
  State<ParentToChildExample> createState() => _ParentToChildExampleState();
}

class _ParentToChildExampleState extends State<ParentToChildExample> {
  String _selectedValue = '未选择';

  void _onValueSelected(String value) {
    setState(() {
      _selectedValue = value;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('子向父传值')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              '选中的值: $_selectedValue',
              style: Theme.of(context).textTheme.titleLarge,
            ),
            const SizedBox(height: 20),
            ChildSelector(
              onSelected: _onValueSelected,
              options: const ['选项1', '选项2', '选项3'],
            ),
          ],
        ),
      ),
    );
  }
}

class ChildSelector extends StatelessWidget {
  final Function(String) onSelected;
  final List<String> options;

  const ChildSelector({
    Key? key,
    required this.onSelected,
    required this.options,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return DropdownButton<String>(
      value: options.first,
      onChanged: (String? newValue) {
        if (newValue != null) {
          onSelected(newValue);
        }
      },
      items:
          options.map<DropdownMenuItem<String>>((String value) {
            return DropdownMenuItem<String>(value: value, child: Text(value));
          }).toList(),
    );
  }
}

// 示例4: 跨组件状态管理 - InheritedWidget
class InheritedData extends InheritedWidget {
  const InheritedData({Key? key, required this.data, required Widget child})
    : super(key: key, child: child);

  final int data; // 需要在子树中共享的数据

  // 定义一个便捷方法，方便子树中的widget获取共享数据
  static InheritedData? of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<InheritedData>();
  }

  // 该回调决定当data发生变化时，是否通知子树中依赖data的Widget
  @override
  bool updateShouldNotify(InheritedData oldWidget) {
    return oldWidget.data != data;
  }
}

class InheritedWidgetExample extends StatefulWidget {
  const InheritedWidgetExample({Key? key}) : super(key: key);

  @override
  State<InheritedWidgetExample> createState() => _InheritedWidgetExampleState();
}

class _InheritedWidgetExampleState extends State<InheritedWidgetExample> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return InheritedData(
      data: _counter,
      child: Scaffold(
        appBar: AppBar(title: const Text('InheritedWidget示例')),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const ShowDataWidget(),
              ElevatedButton(
                onPressed: _incrementCounter,
                child: const Text('增加计数'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class ShowDataWidget extends StatelessWidget {
  const ShowDataWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // 获取InheritedWidget中的数据
    final data = InheritedData.of(context)?.data ?? 0;

    return Text('当前计数: $data', style: Theme.of(context).textTheme.titleLarge);
  }
}

// 主应用入口
void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter状态管理示例',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('状态管理示例')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () {
                Navigator.of(context).push(
                  MaterialPageRoute(builder: (_) => const CounterWidget()),
                );
              },
              child: const Text('基础状态管理示例'),
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                Navigator.of(
                  context,
                ).push(MaterialPageRoute(builder: (_) => const ParentWidget()));
              },
              child: const Text('父向子传值示例'),
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                Navigator.of(context).push(
                  MaterialPageRoute(
                    builder: (_) => const ParentToChildExample(),
                  ),
                );
              },
              child: const Text('子向父传值示例'),
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                Navigator.of(context).push(
                  MaterialPageRoute(
                    builder: (_) => const InheritedWidgetExample(),
                  ),
                );
              },
              child: const Text('InheritedWidget示例'),
            ),
          ],
        ),
      ),
    );
  }
}
